package org.springframework.orm.ibatis.support;

import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.orm.ibatis.SqlMapClientTemplate;

import com.ibatis.sqlmap.client.SqlMapClient;

public final class DefaultSqlMapClientCluster implements SqlMapClientCluster, InitializingBean {
	private SqlMapClient masterClient;
	private SqlMapClient[] slaveClients;
	private SqlMapClientTemplate masterTemplate;
	private SqlMapClientTemplate[] slaveTemplates;
	
	/**
	 * Optional.
	 */
	public void setMasterSqlMapClient(SqlMapClient sqlMapClient) {
		this.masterClient = sqlMapClient;
	}

	/**
	 * Mandantory.
	 */
	public void setSlaveSqlMapClients(List<SqlMapClient> sqlMapClients) {
		this.slaveClients = sqlMapClients.toArray(new SqlMapClient[sqlMapClients.size()]);
	}

	public void afterPropertiesSet() throws Exception {
		if (masterClient != null) {
			this.masterTemplate = new SqlMapClientTemplate(this.masterClient);
		}
		
		if (slaveClients == null) {
			throw new IllegalArgumentException("slaveSqlMapClients is required");
		}
		slaveTemplates = new SqlMapClientTemplate[slaveClients.length];
		for (int i = 0; i < slaveClients.length; i++) {
			SqlMapClient slaveClient = slaveClients[i];
			slaveTemplates[i] = new SqlMapClientTemplate(slaveClient);
		}
	}

	public SqlMapClientTemplate getMasterSqlMapClientTemplate() {
		if (masterTemplate == null) {
			throw new IllegalStateException("Master SqlMapClientTemplate was not given");
		}
		return masterTemplate;
	}
	
	public SqlMapClientTemplate getSlaveSqlMapClientTemplate(int partition) {
		return slaveTemplates[partition];
	}
	
	public SqlMapClient getMasterSqlMapClient() {
		if (masterClient == null) {
			throw new IllegalStateException("Master SqlMapClient was not given");
		}
		return masterClient;
	}
	
	public SqlMapClient getSlaveSqlMapClient(int partition) {
		return slaveClients[partition];
	}
	
	public int getNumberOfSlaves() {
		return slaveClients.length;
	}
}
